<?php
/**
 * Created by MY_MIND.
 * User: WDJ
 * Date: 2018/7/6 0006
 * Time: 10:36
 */
namespace app\index\model;

use \think\Model;
use \think\Db;
use \think\Config;
use \think\Request;


/**
 * 18位订单规则生成说明，购买类型说明
 * 2位前缀 + 10位时间戳 + 6位随机字符串
 * 旗力币购买前缀：QA       类型  1
 * 房卡购买前缀：RA        类型  2
 * 卡包购买前缀：PA        类型  3
 * 道具购买前缀：TA        类型  4
 */
class Shopping extends Model
{

    public $request;
    public $userInfo;
    public $discount;       //游戏玩家VIP等级折扣
    public function __construct()
    {
        parent::__construct();
        $this->request  =   Request::instance();
        //查看游戏玩家的存在性，计算VIP等级的折扣
        $this->userInfo       =   getSqlConnec('QPAccountsDB_CHUI', 'AccountsInfo')->where(['UserID' => $this->request->post()['uid']])->find();
        if($this->userInfo){
            //如果已经到期了，说明等级为0
            $level          =   time() > strtotime($this->userInfo['VIPDueDate']) ? 0 : $this->userInfo['VIPLevel'];

            //根据VIP等级查找折扣
            $this->discount =   getSqlConnec('QPTreasureDB_CHUI', 'VIPConfig')->where(['VIPLevel' => $level])->find()['DisCount'];
        }else{
            $this->discount =   1;
        }
    }

    /**
     * 购买房卡
     * uid      游戏玩家ID
     * package  套餐ID
     */
    public function buyCard()
    {
        $post       =   $this->request->post();

        //根据套餐ID查找相应的对应关系
        $convert    =   Db::name('convert')->where(['id' => $post['package']])->find();
        if(!$convert){
            return [false, '无效套餐'];
        }

        $create_time        =   time();
        //游戏玩家减旗力币Score，加房卡InsureScore
        $nums               =   $convert['card_one'];
        $price              =   ceil($this->discount * $convert['coin_one']);

        //判断玩家是否有足够的旗力币
        $treasure           =   getSqlConnec('QPTreasureDB_CHUI', 'GameScoreInfo')->where(['UserID' => $this->userInfo['UserID']])->field('Score, INsureScore')->find();
        if($treasure['Score'] < $price){
            return [false, '旗力币不足'];
        }

        //考虑版本兼容性问题
        if(version_compare(THINK_VERSION , '5.0.18' , '>')){
            $exp['Score']           =   Db::raw("Score-$price");
            $exp['InsureScore']     =   Db::raw("InsureScore+$nums");
        }else{
            $exp['Score']           =   ['exp' , "Score-$price"];
            $exp['InsureScore']     =   ['exp' , "InsureScore+$nums"];
        }
        $buyResult         =   getSqlConnec('QPTreasureDB_CHUI', 'GameScoreInfo')->where(['UserID' => $this->userInfo['UserID']])->update(['Score' => $exp['Score'], 'InsureScore' => $exp['InsureScore']]);
        if($buyResult == false){
            return [false, '购买失败'];
        }

        //添加购买记录
        $data['uid']        =   $post['uid'];
        $data['order_sn']   =   'QA' . time() . createNoncestr(6);
        $data['type']       =   2;
        $data['nums']       =   $nums;
        $data['price']      =   $price;
        $data['name']       =   '房卡';
        $data['create_time']=   $create_time;
        $data['is_pay']     =   1;
        $data['pay_time']   =   time();

        $result     =   Db::name('shop_log')->insert($data);
        if($result !== false){
            return [true, $result];
        }else{
            return [false, '购买失败'];
        }

    }

    /**
     * 购买卡包
     * uid      游戏玩家ID
     * package  套餐ID
     */
    public function buyBag()
    {
        $post       =   $this->request->post();
        //根据套餐ID查找相应的对应关系
        $bag        =   Db::name('bag')->where(['id' => $post['package']])->find();
        if(!$bag){
            return [false, '无效套餐'];
        }

        $create_time        =   time();
        $price              =   ceil($this->discount * $bag['price']);

        //判断玩家是否有足够的旗力币
        $treasure           =   getSqlConnec('QPTreasureDB_CHUI', 'GameScoreInfo')->where(['UserID' => $this->userInfo['UserID']])->field('Score, InsureScore, CardType, CardDueTime')->find();
        if($treasure['Score'] < $price){
            return [false, '旗力币不足'];
        }

        //游戏玩家减旗力币，加卡包
//        $bagTime            =   getSqlConnec('QPTreasureDB_CHUI', 'UserBackPack')->where(['UserID' => $this->userInfo['UserID'], 'GoodType' => 2])->order('DueTime Desc')->limit(1)->find();
        $mircotime          =   substr(explode(' ' , microtime())[0] , 2 , 3);

        //查询是否有卡包在有效期内
        if($treasure && ($endTime = strtotime($treasure['CardDueTime'])) > time()){
            switch ($bag['id']){
                case '1':
                    $dueTime =  date('Y-m-d H:i:s' , $endTime + 24 * 3600) . '.' . $mircotime;
                break;

                case '2':
                    $dueTime =  date('Y-m-d H:i:s' , $endTime + 24 * 3600 * 7) . '.' . $mircotime;
                    break;

                case '3':
                    $dueTime =  date('Y-m-d H:i:s' , $endTime + 24 * 3600 * 30) . '.' . $mircotime;
                    break;

                default:
                    $dueTime =  date('Y-m-d H:i:s' , $endTime + 24 * 3600) . '.' . $mircotime;
                    break;
            }
        }else{
            switch ($bag['id']){
                case '1':
                    $dueTime =  date('Y-m-d H:i:s' , strtotime("+1 day")) . '.' . $mircotime;
                    break;

                case '2':
                    $dueTime =  date('Y-m-d H:i:s' , strtotime("+7 day")) . '.' . $mircotime;
                    break;

                case '3':
                    $dueTime =  date('Y-m-d H:i:s' , strtotime("+30 day")) . '.' . $mircotime;
                    break;

                default :
                    $dueTime =  date('Y-m-d H:i:s' , strtotime("+1 day")) . '.' . $mircotime;
                    break;
            }
        }

        $update['Score']    =   $treasure['Score'] - $price;
        $update['CardDueTime']  =   $dueTime;

        /**
         * 卡包类型以时间长的为主
         */
        if($bag['id'] > $treasure['CardType']){
            $update['CardType'] = $bag['id'];
        }

        //添加购买记录
        $data['uid']        =   $post['uid'];
        $data['order_sn']   =   'PA' . time() . createNoncestr(6);
        $data['type']       =   3;
        $data['nums']       =   1;
        $data['price']      =   $price;
        $data['name']       =   $bag['name'];
        $data['create_time']=   $create_time;
        $data['is_pay']     =   0;
        $data['pay_time']   =   time();

        $result     =   Db::name('shop_log')->insert($data);

        $updateResult       =   getSqlConnec('QPTreasureDB_CHUI', 'GameScoreInfo')->where(['UserID' => $this->userInfo['UserID']])->update($update);
        if($updateResult === false){
            return [false, '购买失败1'];
        }

        $lastInsertId   =   Db::name('shop_log')->getLastInsID();
        Db::name('shop_log')->where(['id' => $lastInsertId])->update(['is_pay' => 1]);
        if($result !== false){
            return [true, date('Y/m/d' , strtotime($dueTime)) . '<br />' . date('H:i' , strtotime($dueTime))];
        }else{
            return [false, '购买失败'];
        }

    }

    /**
     * 购买道具(骰盅)
     * uid      游戏玩家ID
     * package  套餐ID
     */
    public function buyTool()
    {
        $post       =   $this->request->post();
        //根据套餐ID查找相应的对应关系
        $tool       =   Db::name('goods')->where(['id' => $post['package'], 'allow_buy' => 1])->find();
        if(!$tool){
            return [false, '无效套餐'];
        }

        /*if($tool['storage'] < 1){
            return [false, '库存不足'];
        }*/

        if($this->userInfo['VIPLevel'] < $tool['grade']){
            return [false, '等级不够'];
        }

        $create_time        =   time();
        $price              =   ceil($this->discount * $tool['price']);

        //不能重复购买
        $ifBuy              =   getSqlConnec('QPTreasureDB_CHUI', 'UserBackPack')->where(['UserID' => $this->userInfo['UserID'] , 'ImageID' => $tool['image_id'] , 'GoodType' => 1])->find();
        if($ifBuy){
            return [false, '已经拥有'];
        }

        //判断玩家是否有足够的旗力币
        $treasure           =   getSqlConnec('QPTreasureDB_CHUI', 'GameScoreInfo')->where(['UserID' => $this->userInfo['UserID']])->field('Score, INsureScore')->find();
        if($treasure['Score'] < $price){
            return [false, '旗力币不足'];
        }

        //游戏玩家减旗力币，加道具
        $add['UserID']      =   $this->userInfo['UserID'];
//        $add['GoodID']      =   $tool['id'];
        $add['GoodType']    =   1;
        $add['IsInUse']     =   0;
//      $add['GoodLevel']   =   '';           物品等级
        $add['IsForever']   =   1;
        $add['DueTime']     =   date('Y-m-d H:i:s' , time()). '.' . substr(explode(' ' , microtime())[0] , 2 , 3);
        $add['TradeInfo']   =   '购买道具';
        $add['GoodName']    =   $tool['name'];
        $add['ImageID']     =   $tool['image_id'];
//        $add['Effect']      =   $this->request->domain() . $tool['effect'];
        $add['Describtion'] =   $tool['content'];
//      $add['UnClockWay']  =   '';   解锁方式
        $add['Price']       =   $tool['price'];
        $add['VIPLimit']    =   $tool['grade'];
        $add['StockNum']    =   '1';
//      $add['CanBuyAsGift']=   '';
//        dump($add);exit;

        //添加购买记录
        $data['uid']        =   $post['uid'];
        $data['order_sn']   =   'TA' . time() . createNoncestr(6);
        $data['type']       =   4;
        $data['nums']       =   1;
        $data['price']      =   $price;
        $data['name']       =   $tool['name'];
        $data['create_time']=   $create_time;
        $data['is_pay']     =   0;
        $data['pay_time']   =   time();

        $result     =   Db::name('shop_log')->insert($data);

        $addResult          =   getSqlConnec('QPTreasureDB_CHUI', 'UserBackPack')->insert($add);
        $decResult          =   getSqlConnec('QPTreasureDB_CHUI', 'GameScoreInfo')->where(['UserID' => $this->userInfo['UserID']])->setDec('Score', $price);
        if(!$addResult || !$decResult){
            return [false, '购买失败'];
        }

        $lastInsertId   =   Db::name('shop_log')->getLastInsID();
        if(Db::name('shop_log')->where(['id' => $lastInsertId])->update(['is_pay' => 1]) !== false){
            return [true, $result];
        }else{
            return [false, '购买失败'];
        }

    }

    /**
     * 绑定邀请码
     * uid      游戏玩家ID
     * code     邀请码
     */
    public function codeBind()
    {
        $post   =   $this->request->post();
        //查找邀请码
        $code       =   Db::name('ratio')->where(['request' => $post['code']])->find();
        if(!$code){
            return [false, '邀请码不存在'];
        }

        //查找是否已经绑定邀请码
        $exist      =   Db::name('relation')->where(['invitation_code' => $post['code'] , 'game_user_id' => $post['uid']])->find();
        if($exist){
            return [false, '已经绑定过邀请码'];
        }

        //插入邀请码
        $insert     =   Db::name('relation')->insert(['invitation_code' => $post['code'] , 'game_user_id' => $post['uid'] , 'add_time' => time()]);
        if($insert !== false){
            return [true, $insert];
        }else{
            return [false, '绑定失败'];
        }
    }

}
